<?php

namespace App\Http\Controllers\baseinfo;

use Illuminate\Http\Request;
use App\Models\Employee;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class EmployeeController extends Controller
{
    protected $name = '员工档案';
    protected $field = ['employeeid','employeeid1','name','englishname','idcard','iccardnumber','isvirtualemp','deptid','position','worktype','salary',
    'sex','height','weight','tel','education','married','birthday','addr','nowplace','email','qq','wechat','registerplace','registerdate','enterdate',
    'confirmdate','leavedate','leavereason','leavedes','state','emergenttel','emergentadress','emergentlinkname','userid','picturepath1','picturepath2','picturepath3',
    'Native','bank','Polity','talent','school','graduationtime','schoolarea','emergencycontact','zipcode','emergencytel','emergencyaddress','birthplace','residence',
    'mandes','idcardnumber','worknum','efficiency','residentunit','ishrchk','team','skill','isnew','salarytype','basesalary','contractdatebe',
    'contractdateend','comfirmdate','leafdate','leafreason','leafdes','documentplace','istraining','isexam','examscores','workdetail','referrer','referrertel',
    'referreraddress','referrerunit','guarantor','guarantortel','guarantoraddress','guarantorunit','stopinsurance','insurancenum1','insurancenum2','insurancenum3',
    'allinsurance','monthinsurance','insuranceend','insurancebe','isinsurance1','isinsurance2','isinsurance3','isinsurance4','isinsurance6','isinsurance5','isinsurance7',
    'resume','manrecord','homedes','contractdes','guaranteedes'];
    protected $find=['a.id','a.employeeid','a.employeeid1','a.name','a.englishname','a.idcard','a.iccardnumber','a.isvirtualemp','a.deptid','a.position','a.worktype','a.salary',
    'a.sex','a.height','a.weight','a.tel','a.education','a.married','a.birthday','a.addr','a.nowplace','a.email','a.qq','a.wechat','a.registerplace','a.registerdate','a.enterdate',
    'a.confirmdate','a.leavedate','a.leavereason','a.leavedes','a.state','a.emergenttel','a.emergentadress','a.emergentlinkname','a.userid','a.picturepath1','a.picturepath2','a.picturepath3',
    'a.Native','a.bank','a.Polity','a.talent','a.school','a.graduationtime','a.schoolarea','a.emergencycontact','a.zipcode','a.emergencytel','a.emergencyaddress','a.birthplace','a.residence',
    'a.mandes','b.deptnm','a.idcardnumber','a.worknum','a.efficiency','a.residentunit','a.ishrchk','a.team','a.skill','a.isnew','a.salarytype','a.basesalary','a.contractdatebe',
    'a.contractdateend','a.comfirmdate','a.leafdate','a.leafreason','a.leafdes','a.documentplace','a.istraining','a.isexam','a.examscores','a.workdetail','a.referrer','a.referrertel',
    'a.referreraddress','a.referrerunit','a.guarantor','a.guarantortel','a.guarantoraddress','a.guarantorunit','a.stopinsurance','a.insurancenum1','a.insurancenum2','a.insurancenum3',
    'a.allinsurance','a.monthinsurance','a.insuranceend','a.insurancebe','a.isinsurance1','a.isinsurance2','a.isinsurance3','a.isinsurance4','a.isinsurance6','a.isinsurance5','a.isinsurance7',
    'a.resume','a.manrecord','a.homedes','a.contractdes','a.guaranteedes'];  

    protected $datefield = ['birthday', 'registerdate', 'enterdate', 'confirmdate', 'leavedate', 'graduationtime', 'contractdatebe', 'contractdateend', 'comfirmdate', 'leafdate', 'insuranceend', 'insurancebe'];
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }
    /**
     * 查询员工
     */
    public function find(Request $request)
    {
        try {
            $param = json_decode($request->param, true);
            $employeeid = $this->I($param['empid'] ?? null);
            $name = $this->I($param['empnm'] ?? null);
            $dept = $this->I($param['dept'] ?? null);
            $position = $this->I($param['position'] ?? null);
            $tel = $this->I($param['tel'] ?? null);
            $state = $this->I($param['state'] ?? null);
            $entrydatebe = $this->I($param['entrydatebe'] ?? null);
            $entrydateend = $this->I($param['entrydateend'] ?? null);
            $keyvalue = $this->I($param['keyvalue'] ?? null);
            $page = intval($this->I(param: $param['page'] ?? 1));
            $pagecount = intval($this->I($param['pagecount'] ?? 10));
            $where = 'a.isdel=0 ';
            if (!empty($name)) {
                $where .= ' and a.name like "%' . $name . '%" ';
            }
            if (!empty($employeeid)) {
                $where .= " and a.employeeid = '$employeeid' ";
            }
            if (!empty($dept)) {
                $where .= " and (b.deptid = '$dept' or b.deptnm like '%$dept%') ";
            }
            if (!empty($position)) {
                $where .= " and a.position = '$position' ";
            }
            if (!empty($tel)) {
                $where .= " and a.tel = '$tel' ";
            }
            if (!empty($state)) {
                $where .= " and a.state = '$state' ";
            }
            if (!empty($entrydatebe)) {
                $where .= " and a.enterdate >= '$entrydatebe' ";
            }
            if (!empty($entrydateend)) {
                $where .= " and a.enterdate < '$entrydateend 23:59:59' ";
            }
            if (!empty($keyvalue)) {
                $where .= " and (a.employeeid = '$keyvalue' or a.name = '$keyvalue') ";
            }
            $temp = DB::table('employee as a')
                ->leftjoin(
                    'dept as b',
                    function ($join) {
                        $join->on('a.deptid', '=', 'b.deptid')
                            ->where('b.isdel', '=', 0);
                    }
                ) // 多表连接
                ->select($this->find) // 确保没有多余的空格
                ->whereRaw($where)
                ->paginate($pagecount, ['id'], 'page', $page)
                ->toArray(); // 控制页码，默认每页 10 条
            $Employee = $temp['data'];
            $allcount = $temp['total'];
            foreach ($Employee as $key) {
                $key->age = $this->getdatediff($key->birthday, date('Y-m-d H:i:s'));
            }
            return $this->ajaxReturn(['code' => 1, 'msg' => $this->name . '|查询成功!', 'count' => $allcount, 'data' => $Employee, 'where' => $where]);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|查询失败!','error'=>$e->getMessage()]);
        }
    }

    /**
     * 查询员工详情
     */
    public function finddetail(Request $request)
    {
        try {
            $param = json_decode($request->param, true);
            $id = $this->I($param['id'] ?? null);
            if (empty($id)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . 'ID不能为空！']);
            }
            $where = "a.id='$id'";
            $Employee = DB::table('employee as a')
                ->leftjoin(
                    'dept as b',
                    function ($join) {
                        $join->on('a.deptid', '=', 'b.deptid')
                            ->where('b.isdel', '=', 0);
                    }
                )
                ->select($this->find) // 确保没有多余的空格
                ->whereRaw($where)
                ->get();
            $nowpicture = [];
            foreach ($Employee as $key) {
                if ($key->picturepath1) {
                    $nowpicture[] = $this->domainurl($key->picturepath1);
                }
                if ($key->picturepath2) {
                    $nowpicture[] = $this->domainurl($key->picturepath2);
                }
                if ($key->picturepath3) {
                    $nowpicture[] = $this->domainurl($key->picturepath3);
                }
                $key->age = $this->getdatediff($key->birthday, date('Y-m-d H:i:s'));
                $key->picturepath = $nowpicture;
            }
            return $this->ajaxReturn(['code' => 1, 'msg' => $this->name . '|查询成功!', 'data' => $Employee]);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|查询失败!','error'=>$e->getMessage()]);
        }
    }


    /**
     * 保存员工
     */
    public function save(Request $request)
    {
        try {
            $param = json_decode($request->param, true);
            $id = $this->I($param['id'] ?? null);
            $isnew = false;
            if (empty($id)) {
                $isnew = true;
            }
            $list = [];
            if (empty($param)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|保存参数为空']);
            }
            foreach ($param as $key => $value) {
                if (in_array($key, $this->field)) {
                    $list[$key] = $value;
                }
            }
            if (empty($list) && !isset($list['picturepath']) && !isset($param['picturepath']) && !isset($param['delpicture'])) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '没有需要处理的数据']);
            }
            //如果有图片删除，先清空路径信息
            if (isset($param['delpicture'])) {
                $list['picturepath1'] = null;
                $list['picturepath2'] = null;
                $list['picturepath3'] = null;
            }
            if (isset($param['picturepath'])) {
                $pic = 'picturepath';
                $i = 1;
                foreach ($param['picturepath'] as $key) {
                    $sart = strpos($key, '/uploads');
                    $list[$pic . $i] = substr($key, $sart, 500);
                    ;
                    $i++;
                }
            }
            //新增
            $where = '';
            if ($isnew) {
                $empnm=$list['name'];
                $type = '新增';
                if (empty($list['employeeid'])) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => '新增失败!员工ID不能为空']);
                }
                if (empty($list['name'])) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => '新增失败!员工姓名不能为空']);
                }
                $FSQL = "  select * from employee where isdel=0 and (employeeid='" . $list['employeeid'] . "' or name='" . $list['name'] . "')";
                if (!empty(DB::select($FSQL))) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => '员工ID或姓名已经存在,不可重复']);
                }
                //新增
                $res = Employee::create($list);
                if (empty($res)) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|新增失败!']);
                }
                $where = " a.employeeid='" . $list['employeeid'] . "' and a.isdel=0 ";
            } else {
                $type = '修改';
                $where = " a.id='$id' ";
                $list['synstate'] = 0;
                //修改   
                $uptab = Employee::find($id);
                $uptab->update($list);
                $empnm=$uptab['name'];
            }
            //如果有图片删除，则删除图片
            if (isset($param['delpicture'])) {
                foreach ($param['delpicture'] as $key) {
                    $this->removefilebase($key);
                }
            }
            $Employee = DB::table('employee as a')
                ->join('dept as b', 'a.deptid', '=', 'b.deptid')
                ->select($this->find)
                ->whereRaw($where)
                ->get();
            $nowpicture = [];
            foreach ($Employee as $key) {
                $key->age = $this->getdatediff($key->birthday, date('Y-m-d H:i:s'));
                if ($key->picturepath1) {
                    $nowpicture[] = $this->domainurl($key->picturepath1);
                }
                if ($key->picturepath2) {
                    $nowpicture[] = $this->domainurl($key->picturepath2);
                }
                if ($key->picturepath3) {
                    $nowpicture[] = $this->domainurl($key->picturepath3);
                }
                $key->age = $this->getdatediff($key->birthday, date('Y-m-d H:i:s'));
                $key->picturepath = $nowpicture;
            }
            //记录日志
            $this->log(['type' => $type, 'billcaption' => '人事档案', 'des' => '操作人[' . $type . ']了人员[' . $empnm . '],数据为[' . json_encode($list) . ']']);
            return $this->ajaxReturn(['code' => 1, 'msg' => $this->name . '保存成功!', 'nowdata' => $Employee]);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|保存失败!','error'=>$e->getMessage()]);
        }
    }
    /**
     * 删除员工
     */
    public function delete(Request $request)
    {
        try {
            $param = json_decode($request->param, true);
            $id = $this->I($param['id'] ?? null);
            if (empty($id)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '删除失败!人员ID为空']);
            }
            $idarr = explode(',', $id);
            if (sizeof($idarr) == 1) {
                $uptab = Employee::find($id);
                if (empty($uptab)) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => '删除失败!人员不存在']);
                }
                $uptab->isdel = 1;
                $res = $uptab->save();
                if (empty($res)) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => '删除失败!']);
                }
                //记录日志
                $this->log(['type' => '删除', 'billcaption' => '人事档案', 'des' => '操作人[删除]了人员[' . $uptab->name . '],ID为[' . $uptab->employeeid . ']']);
            } else {
                $Employee = Employee::whereIn('id', $idarr)->get();
                $namearr = [];
                foreach ($Employee as $key) {
                    $namearr[] = $key->name;
                }
                $EXESQL = "UPDATE employee SET isdel=1 WHERE id in($id)";
                DB::update($EXESQL);
                //记录日志
                $this->log(['type' => '删除', 'billcaption' => '人事档案', 'des' => '操作人[批量删除]了人员[' . implode(',', $namearr) . ']']);
            }
            return $this->ajaxReturn(['code' => 1, 'msg' => '删除成功！']);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|删除失败!','error'=>$e->getMessage()]);
        }
    }
    /**
     * excel导入
     */
    public function excelimport(Request $request)
    {
        try {
            $param = json_decode($request->param, true);
            if (empty($param)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|导入失败!数据为空!']);
            }
            $i = 2;
            //获取所有部门数据
            $FSQL = "select deptid from dept where isdel=0";
            $dept = DB::select($FSQL);
            $deptkey = [];
            foreach ($dept as $key) {
                $deptkey[$key->deptid] = 1;
            }
            //获取所有员工数据
            $FSQL = "select name,employeeid from employee where isdel=0";
            $Employee = DB::select($FSQL);
            $empkey = [];
            $empkeyreapt = [];
            foreach ($Employee as $key) {
                $empkey[$key->employeeid] = 1;
                $empkeyreapt[$key->name] = $key->employeeid;
            }
            $indata = [];
            $updata = [];
            $empkeynm = [];
            $empkeyid = [];
            $iscover = $param['iscover'];
            $data = $param['data'];
            foreach ($data as $key) {
                $employeeid = trim($key['employeeid'] ?? null);
                $name = trim($key['name'] ?? null);
                $deptid = trim($key['deptid'] ?? null);
                if (empty($employeeid)) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => '导入失败!第|' . $i . '|行员工ID不能为空!']);
                }
                if (empty($name)) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => '导入失败!第|' . $i . '|行员工姓名不能为空!']);
                }
                if (empty($deptid)) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => '导入失败!第|' . $i . '|行员工所属部门不能为空!']);
                }
                if (in_array($name, $empkeynm)) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => '导入失败!第|' . $i . '|行员工姓名出现重复!']);
                }
                if (in_array($employeeid, $empkeyid)) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => '导入失败!第|' . $i . '|行员工id出现重复!']);
                }
                if (($deptkey[$deptid] ?? null) !== 1) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => '导入失败!第|' . $i . '|行员工部门编号不存在!']);
                }
                if (($empkeyreapt[$name] ?? null) != null && ($empkeyreapt[$name] ?? null) != $employeeid) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => '导入失败!第|' . $i . '|行员工姓名已经被使用!']);
                }
                $empkeynm[] = $name;
                $empkeyid[] = $employeeid;
                $obj = [];
                //组装需要处理的字段
                foreach ($key as $field => $value) {
                    //字段是否存在校验
                    if (in_array($field, $this->field)) {
                        //日期校验
                        if (in_array($field, $this->datefield) && strtotime($value) == false) {
                            $obj[$field] = null;
                        } else {
                            $obj[$field] = $value;
                        }
                    }
                }
                if (($empkey[$employeeid] ?? null) == 1) {
                    //修改
                    $updata[] = $obj;
                } else {
                    $obj['created_at'] = date('Y-m-d H:i:s');
                    //新增
                    $indata[] = $obj;
                }
                $i++;
            }
            if (!empty($indata)) {
                $res = DB::table('employee')->insert($indata);
                if (empty($res)) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|导入失败!']);
                }
            }
            //记录日志
            $this->log(['type' => 'excel导入', 'billcaption' => '人事档案', 'des' => '操作人进行了excel导入,数据为|[' . json_encode($data) . ']']);
            return $this->ajaxReturn(['code' => 1, 'msg' => '导入成功！', 'indata' => $indata, 'updata' => $updata]);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '导入失败!' ,'error'=>$e->getMessage()]);
        }
    }
}
